package com.jose.photogallery.domain;

import com.jose.photogallery.domain.DAOT.Transactable;

public class PhotogalleryUtil {

	public static boolean hasVoted(String photoId, String userId){
		PhotogalleryDAO dao = new PhotogalleryDAO();
		String key = getRatingKey(photoId, userId);
		
		if ( dao.getRating(key) != null)
			return true;
		else
			return false;
		
	}
	
	private static String getRatingKey(String photoId, String userId){
		return photoId + "-" + userId;
	}
	
	public static void setRating(int vote, String photoId, String userId){
		PhotogalleryDAO dao = new PhotogalleryDAO();
		// Create rating object for this vote
		Rating rating = new Rating();
		rating.setKey(getRatingKey(photoId, userId));
		rating.setBlobKey(photoId);
		rating.setRating(vote);
		rating.setUser(userId);
		dao.saveRating(rating);
		
		// Update rating in photo object
		
		
		final String PHOTO_ID = photoId;
		final int VOTE = vote;
		
		
		// Create transaction to save the vote		
		DAOT.repeatInTransaction(new Transactable() {
			@Override
			public void run(DAOT daot) {
				Photo photo = daot.ofy().find(Photo.class, PHOTO_ID);
				photo.updateRating(VOTE);
				daot.ofy().put(photo);
			}
		});	
		
	}
}
